package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
)

/*
net/http包 是go语言内置包
涵盖了http请求的客户端和服务端
 */

/*客户端  浏览器行为
 */
func main() {
	//客户端发起http请求  去请求百度
	request_client("http://newspaper.jcrb.com/2023/20230407/20230407_002/20230407_001_01_38.jpg")
}

func request_client(url string) {
	//创建一个客户端
	client := http.Client{}
	//创建一个新的请求
	r,_ := http.NewRequest("GET", url,nil)
	//客户端发送请求
	response, e := client.Do(r)
	if e != nil {
		fmt.Println("发送请求程序异常")
		return
	}
	fmt.Println("请求的状态码：",response.StatusCode)
	fmt.Println(response.Body)
	defer response.Body.Close()
	data, err := io.ReadAll(response.Body)
	err = ioutil.WriteFile("photo.jpg",data,0666)
	if err != nil {
		fmt.Println("下载失败")
	}
}

//下载图片
func download_pic(url string){
	client := http.Client{}
	response, e := client.Get(url)
	if e != nil {
		fmt.Println("下载图片错误:",e)
		return
	}
	file, err := os.Create("sctl.png")
	if err != nil {
		fmt.Println("打开文件失败",err)
		return
	}
	data := response.Body
	read := bufio.NewReader(data)
	writer := bufio.NewWriter(file)
	down_pic, _ := io.Copy(writer, read)
	fmt.Println(down_pic)
	defer data.Close()
}